<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;

use Common\Api\MailApi;
use User\Api\AccountApi;
use Wechat\Api\ClientApi;
use Wechat\Api\QrCodeApi;

/**
 * 后台用户信息控制器
 * TODO: 将会在这里增加更新微信资料以及更新UCENTER的功能
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class MemberController extends UserController {

    /**
     * 用户资料查看
     * @author Tealun Du
     */
    public function myInfo() {
        if(I('get.uid')){
            if(!is_administrator(UID) && !in_group(UID,2)){
                $uid= UID;//非管理员只能看到自己的账户信息
            }else{
                $uid= I('get.uid');//管理员可以看到别人的信息
            }
        }else{
            $uid=UID;
        }
        $info = $this->getUserInfo($uid);
        $this->meta_title='我的账户信息';
        $this->assign('info' , $info);
        $this->display('index');
    }

    /**
     * 修改信息初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updateInfo() {

        $uid = I('get.uid');

        if ( !$uid ) {
            $uid = UID;
        }

        if ( !is_administrator() && $uid != UID ) {
            //不在管理员组 输出错误信息
            !in_group(UID,2) && $this->error("您没有权限编辑他人信息");
            exit;
        }

        $info['uid']=$uid;
        $ucenter = M('Ucenter_member')->field('username,email,mobile')->find($uid);//查找UCENTER数据表
        $info = array_merge($info,$ucenter , M('Member')->field(array( sex , nickname , status , honour , description , birthday , img , qq , weibo , weixin , country , province , city , street ))->find($uid));

        $this->meta_title='编辑账户信息';
        $this->assign('info' , $info);
        $this->display('edit');
    }

    /**
     * 修改信息提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitInfo() {
        //获取参数
        $nickname = I('post.nickname');
        $password = I('post.password');
        empty( $nickname ) && $this->error('请输入昵称');
        empty( $password ) && $this->error('请输入密码');

        //密码验证
        $User = new AccountApi();
        $uid = $User->login(UID , $password , 4);
        ( $uid == -2 ) && $this->error('管理员密码不正确');

        $Member = D('Member');
        $data = $Member->create();
        if ( !$data ) {
            $this->error($Member->getError());
        }

        $res = $Member->where(array( 'uid' => I('post.uid') ))->save($data);

        if ( $res ) {
            $nickname = M('Member')->where(array( 'uid' => UID ))->getField('nickname');
            $user = session('user_auth');
            $user['username'] = $nickname;
            session('user_auth' , $user);
            session('user_auth_sign' , data_auth_sign($user));

            $url = $User->buildResetPasswordUrl(I('post.uid'));

            $Mail = new MailApi();
            $mailStatus = $Mail->sendMail(I('post.uid'),2,array('urlForgetPassword'=>$url));//发送邮件给变动资料的账户邮箱
            $this->success('信息修改成功！'.$mailStatus['info']);
        } else {
            $this->error('修改信息失败！');
        }
    }

    /**
     * 获取用户详细信息
     * @param $uid
     *
     * @return array
     */
    private function getUserInfo($uid){
        $info['ucenter'] = M('Ucenter_member')->where('`id` = '.$uid)->getField('id,username,email,mobile');
        $info['ucenter'] = $info['ucenter'][$uid];
        $info['member'] = M('Member')->find($uid);

        if(C('WECHAT_GHID')){
            $Client = new ClientApi();
            $info['wechat'] = $Client->getInfo(
                $Client->getOpenidByUid($uid),'nickname,sex,headimgurl'
            );
            if(empty($info['wechat'])){
                $info['wechat']=array('尚未绑定' =>'<span data="" id="bindQrcode" class="btn btn-primary">点击绑定</span><img id="qrcodeImage" style="display:none" src="" alt="扫码绑定微信帐号"  width="200px"/><span id="bindStatus"></span>');
            }
        }

        return $info;
    }

    /**
     * 用于前端轮询的绑定帐号方法
     */
    public function bind(){
        if(IS_POST || IS_AJAX){
            //先获取提交的bind参数是否是true
            $bind=I('post.bind');
            //如果是true 进入获取绑定二维码流程
            if($bind == true){
                $uid = I('post.uid');//获取提交的uid

                $QrCode = new QrCodeApi();//实例化微信qrcode类
                $ticket = $QrCode->create('Admin' , '',300);//创建一个有效时间为5分钟的临时二维码
                if($ticket){//获取成功后缓存临时二维码的处理参数
                    S($ticket,array(
                        'action_name'=>'QR_SCENE',
                        'module'=>'Wechat',
                        'controller'=>'Client',
                        'mdr'=>'Event',
                        'action'=>'bind',
                        'data'=>array(
                            'ticket'=>$ticket,
                            'uid'=>$uid
                        )
                    ),300);
                    //组织AJAX返回前端的数据
                    $info = array(
                        'ticket'=>$ticket,
                        'qrcode'=>get_qr_code($ticket),
                        'tips'=>'请扫描二维码'
                    );
                    //ajax返回前端
                    $this->success($info);
                }else{//创建二维码失败返回前端
                    $this->ajaxReturn(0,'获取二维码失败',0);
                }
            //如果提交的bind参数为false,则判断为扫描状态轮询
            }else{
                $ticket = I('post.ticket');//获取提交的ticket参数来判断是要轮询哪个临时二维码
                $s = S($ticket);
                if(!$s){//查看有没有缓存，没有则返回失效
                    return $this->error('二维码已失效');
                }else{//有缓存则查看是否已写入openid，写入是在缓存中指定的模块的指定控制器层方法中执行
                    if($s['data']['openid']){
                        S($ticket,NULL);//如果有openid说明绑定完成了，清空Ticket缓存
                        $this->success('绑定成功');
                    }else{//没有openid则说明还没有扫描，或者扫描出错，没有绑定
                        $this->error('请扫描二维码');
                    }
                }
            }
        }
    }

}
